﻿using System;
using System.IO;
using System.Runtime.Serialization;
using System.Xml;

namespace Game.Types
{
    public class GameTypeSerializer
    {
        public static string ToString(VehicleType vehicleType)
        {
            DataContractSerializer serializer = 
                new DataContractSerializer(typeof(VehicleType));
            StringWriter stringWriter = new StringWriter();
            XmlWriter writer = XmlWriter.Create(stringWriter);
            writer.Settings.Indent = true;
            try
            {
                serializer.WriteObject(writer, vehicleType);
            }
            catch (Exception e)
            {
                Console.WriteLine(e.Message);
            }
            
            return stringWriter.ToString();
        }
        
        public static VehicleType ToVehicleType(string xml)
        {
            StringReader stringReader = new StringReader(xml);
            XmlReader reader = XmlReader.Create(stringReader);
            DataContractSerializer serializer =
                new DataContractSerializer(typeof(VehicleType));
            
            VehicleType result = null;
            if (xml.Trim().Length > 0)
            {
                result = (VehicleType)serializer.ReadObject(reader);
            }
            
            return result;
        }
    }
}
